import os
import re

import httpx


def puml_to_svg(puml_file_name: str):
    puml_suffix = '.puml'
    if not puml_file_name.endswith(puml_suffix):
        raise Exception('file extension is not puml')
    file_name = puml_file_name.removesuffix(puml_suffix)
    os.system(f'cat {puml_file_name} | java -jar plantuml-1.2024.4.jar -tsvg -pipe > {file_name}.svg')


def deflate_and_encode(plantuml_text: str):
    """zlib compress the plantuml text and encode it for the plantuml server.
    """
    import base64
    import string
    from zlib import compress
    import six
    if six.PY2:
        from string import maketrans
    else:
        maketrans = bytes.maketrans
    __author__ = 'Doug Napoleone, Samuel Marks, Eric Frederich'
    __email__ = 'doug.napoleone+plantuml@gmail.com'
    plantuml_alphabet = string.digits + string.ascii_uppercase + string.ascii_lowercase + '-_'
    base64_alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
    b64_to_plantuml = maketrans(base64_alphabet.encode('utf-8'), plantuml_alphabet.encode('utf-8'))
    
    zlibbed_str = compress(plantuml_text.encode('utf-8'))
    compressed_string = zlibbed_str[2:-4]
    return base64.b64encode(compressed_string).translate(b64_to_plantuml).decode('utf-8')


# 单例客户端
_client_instance = None


def get_client_instance() -> httpx.Client:
    global _client_instance
    if _client_instance is None:
        _client_instance = httpx.Client()
    return _client_instance


def puml_to_png(puml_code: str, server_ip: str = '192.168.124.37', server_port: int = 8080) -> bytes:
    plantuml_encode = deflate_and_encode(puml_code)
    client = get_client_instance()
    response = client.get(
        url=f'http://{server_ip}:{server_port}/plantuml/png/{plantuml_encode}'
    )
    return response.content


def get_puml_from_markdown(markdown: str) -> str:
    m = re.search(r'```plantuml(.*)```', markdown, re.DOTALL | re.IGNORECASE)
    if m is None:
        return ''
    else:
        return m.groups()[0].strip()
